// const API_URL = 'https://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=3fd2be6f0c70a2a598f084ddfb75487c&page=1'
const API_URL =
  // "https://api.wmdb.tv/api/v1/top?type=Imdb&skip=0&limit=50&lang=Cn";
  "https://api.wmdb.tv/api/v1/top?type=Imdb";
const IMG_PATH = "https://image.tmdb.org/t/p/w1280";

// const SEARCH_API =
//   'https://api.themoviedb.org/3/search/movie?api_key=3fd2be6f0c70a2a598f084ddfb75487c&query="';
const main = document.getElementById("main");
const form = document.getElementById("form");
const search = document.getElementById("search");

// Get initial movies
getMovies(API_URL);

async function getMovies(url) {
  /* 发送请求 */
  const res = await fetch(url).then((data) => {
    return data.json();
  });
  console.log(res);
  showMovies(res);
}

function showMovies(movies) {
  main.innerHTML = "";
  /* 循环拿到的数据 */
  movies.forEach((movie) => {
    // const { alias, poster_path, vote_average, overview } = movie;
    /* 解构出需要用的到数据 */
    const { data, doubanRating } = movie;

    const { name, poster, description } = data[0];
    /* 创建一个div元素 */
    const movieEl = document.createElement("div");
    /* 给div元素添加上movie类样式 */
    movieEl.classList.add("movie");

    movieEl.innerHTML = `
            <img src="${poster}" alt="${name}">
            <div class="movie-info">
          <h3>${name}</h3>
          <span class="${getClassByRate(doubanRating)}">${doubanRating}</span>
            </div>
            <div class="overview">
          <h3>概述</h3>
          ${description}
        </div>
        `;
    /* 将创建的div添加进main元素中 */
    main.appendChild(movieEl);
  });
}

function getClassByRate(vote) {
  if (vote >= 8) {
    return "green";
  } else if (vote >= 5) {
    return "orange";
  } else {
    return "red";
  }
}

form.addEventListener("submit", (e) => {
  e.preventDefault();

  const searchTerm = search.value;

  if (searchTerm && searchTerm !== "") {
    const SEARCH_API = `https://api.wmdb.tv/api/v1/movie/search?q=${searchTerm}&limit=10&skip=0&lang=Cn`;
    getMovies(SEARCH_API);

    search.value = "";
  } else {
    window.location.reload();
  }
});
